package com.cskaoyan.mall.dao.mall;

import com.cskaoyan.mall.model.bo.mall.AddOrderBO;
import com.cskaoyan.mall.model.bo.mall.CartBO;
import com.cskaoyan.mall.model.bo.mall.CartListBO;
import com.cskaoyan.mall.model.bo.mall.SendCommentBO;
import com.cskaoyan.mall.model.vo.admin.GetGoodsIdVO;
import com.cskaoyan.mall.model.vo.mall.*;
import com.cskaoyan.mall.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;

public class MallOrdersDaoImpl implements MallOrdersDao{
//    {token: "admin", goodsDetailId: 1853, state: 0, num: 1, amount: 11}
    @Override
    public int addOrder(AddOrderBO addOrderBO) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        AddOrdersUserVO addOrdersUserVO = null;
        AddOrdersGoodsIdVO addOrdersGoodsIdVO = null;
        AddOrdersGoodsVO addOrdersGoodsVO = null;
        try {
            addOrdersUserVO = runner.query("select id as userId , address , phone ,recipient , nickname from user where email = ? ",new BeanHandler<>(AddOrdersUserVO.class),addOrderBO.getToken());
            addOrdersGoodsIdVO = runner.query("select goodsId , specname as spec from spec where id = ? ",new BeanHandler<>(AddOrdersGoodsIdVO.class),addOrderBO.getGoodsDetailId());
            addOrdersGoodsVO = runner.query("select name as goods from goods where id = ? ",new BeanHandler<>(AddOrdersGoodsVO.class),addOrdersGoodsIdVO.getGoodsId());
            runner.update("insert into orders (nickname,goodsDetailId,stateId,goodsNum,amount,userId,address,phone,goods,goodsId,spec,name,createtime,hasComment) values (?,?,?,?,?,?,?,?,?,?,?,?,Now(),0)",
                    addOrdersUserVO.getNickname(),
                    addOrderBO.getGoodsDetailId(),
                    addOrderBO.getState(),
                    addOrderBO.getNum(),
                    addOrderBO.getAmount(),
                    addOrdersUserVO.getUserId(),
                    addOrdersUserVO.getAddress(),
                    addOrdersUserVO.getPhone(),
                    addOrdersGoodsVO.getGoods(),
                    addOrdersGoodsIdVO.getGoodsId(),
                    addOrdersGoodsIdVO.getSpec(),
                    addOrdersUserVO.getRecipient());

        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 404;
        }
        return 200;
    }
    //     * {"code":0,"data":
//             * [{"id":2323,
//             * "state":0,
//             * "goodsNum":1,
//             * "amount":200.0,
//             * "goodsDetailId":1238,"
//             * createtime":"2020-08-12 16:28:33","
//             * hasComment":false,
//             * "goods":{"id":478,"img":"http://115.29.141.32:8084/static/image/157123055832115669931721908195203.jpg",
//             * "name":"新品外套",
//             * "goodsDetailId":1238,
//             * "spec":"卡其色",
//             * "unitPrice":200.0}}]}
    @Override
    public List<GetOrderByStateVO> getOrderByState(String token, String state) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        List<GetOrderByStateVO> ordersList = null;
        GetNicknameVO nickname = null;
        GetOrderByStateGoodsVO goods1 = null;
        GetOrderByStateGoodsVO goods2 = null;
        GetGoodsIdVO goodsId = null;
        try {
            nickname = runner.query("select nickname from user where email = ? ",new BeanHandler<>(GetNicknameVO.class),token);
            if (Integer.parseInt(state) != -1) {
                ordersList = runner.query("select id , stateId as state , goodsNum , amount , goodsDetailId , createtime , hasComment from orders where stateId = ? and nickname = ?",
                        new BeanListHandler<>(GetOrderByStateVO.class),state,nickname.getNickname());
            }else {
                ordersList = runner.query("select id , stateId as state , goodsNum , amount , goodsDetailId , createtime , hasComment from orders where nickname = ?",
                        new BeanListHandler<>(GetOrderByStateVO.class),nickname.getNickname());
            }
            for (GetOrderByStateVO order : ordersList) {
                goodsId = runner.query("select goodsId from spec where id = ? ",new BeanHandler<>(GetGoodsIdVO.class),order.getGoodsDetailId());
                goods1 = runner.query("select id , img , name from goods where id = ? ",new BeanHandler<>(GetOrderByStateGoodsVO.class),goodsId.getGoodsId());
                goods2 = runner.query("select specname as spec , unitPrice from spec where id = ? ",new BeanHandler<>(GetOrderByStateGoodsVO.class),order.getGoodsDetailId());
                goods1.setGoodsDetailed(order.getGoodsDetailId());
                goods1.setSpec(goods2.getSpec());
                goods1.setUnitPrice(goods2.getUnitPrice());
                order.setGoods(goods1);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return ordersList;
    }

    @Override
    public int deleteOrder(String id) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        try {
            runner.update("delete from orders where id = ? ",id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 404;
        }
        return 200;
    }

    @Override
    public int settleAccounts(CartListBO cart) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        List<CartBO> cartList = cart.getCartList();
        SetAccountVO getorderspec = null;
        SpecStockNumVO init = null;
        try {
            for (CartBO cartBO : cartList) {
                runner.update("update orders set stateId = ? , goodsNum = ? , amount = ? where id = ? ",
                        1,cartBO.getGoodsNum(),cartBO.getAmount(),cartBO.getId());
                getorderspec = runner.query("select spec , goodsId from orders where id = ?",new BeanHandler<>(SetAccountVO.class),cartBO.getId());
                Integer goodsNum = Integer.parseInt(cartBO.getGoodsNum());
                init = runner.query("select stocknum from spec where specname = ? and goodsId = ?",new BeanHandler<>(SpecStockNumVO.class),getorderspec.getSpec(),getorderspec.getGoodsId());
                if (goodsNum > init.getStocknum()) {
                    return 404;
                }
                Integer realstocknum = init.getStocknum() - goodsNum;
                runner.update("update spec set stocknum = ? where specname = ? and goodsId = ?",realstocknum);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 404;
        }
        return 200;
    }

    @Override
    public int confirmReceive(String id) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        try {
            runner.update("update orders set stateId = ? where id = ? ",3,id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 404;
        }
        return 200;
    }

    @Override
    public int sendComment(SendCommentBO comment) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        BigDecimal averagescore = null;
        GetUserIdVO userId = null;
        try {
//            insert into admin (email,nickname,pwd) values (?,?,?)
            userId = runner.query("select userId as id from orders where id = ?",new BeanHandler<>(GetUserIdVO.class),comment.getOrderId());
            runner.update("insert into comment (content , goodsId , orderId , score , time ,userId) values (?,?,?,?,Now(),?)",
                    comment.getContent(),
                    comment.getGoodsId(),
                    comment.getOrderId(),
                    comment.getScore(),
                    userId.getId());
            averagescore = (BigDecimal) runner.query("select avg(score) from comment where goodsId = ? ",new ScalarHandler(),comment.getGoodsId());
            runner.update("update goods set averagescore = ? ",averagescore);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 404;
        }
        return 200;
    }

    @Override
    public int pay(String id) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        try {
            runner.update("update orders set stateId = ? where id = ? ",1,id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return 404;
        }
        return 200;
    }
}
